package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController

@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;

    //@RequestMapping(value = "/",method = RequestMethod.GET)
    @GetMapping("/")
    public List<Drink> getAll() {
        List<Drink> results = drinkService.getAllDrinks();
//        new ArrayList<>();
//        results.add(Drink.builder().id(1))
//                .name("茉莉花茶")
//                .price(Money.parse("USD 8.00"))
//                .build();
//
    return results;
    }

    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id) {
        log.info("查询饮品id:{}", id);
        Drink drink = Drink.builder().id(1)
                .name("茉莉花茶")
                .price(Money.parse("USD 8.00"))
                .build();
        return drink;
    }

    @PostMapping("/")
    public Drink addNewDrink(@RequestBody ModifyDrinkRequest drink, BindingResult result) {
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                log.error(error.toString());
            }
            return null;

        } else {

            log.info("查询饮品id:{}", drink);
            Drink savedDrink=new Drink();
            BeanUtils.copyProperties(drink,savedDrink);

            drinkService.addNewDrink(savedDrink,drink.getCategoryId());
            return savedDrink;
        }
    }

    @PutMapping("/")
    public Drink modifyDrink(@RequestBody ModifyDrinkRequest request) {
        log.info("修改的饮品:{}", request);
      Drink drink= drinkService.getDrinkById(request.getId());
        BeanUtils.copyProperties(request,drink);
        drinkService.updateDrink(drink);
        return drink;
    }

    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id) {
        log.info("要删除的饮品id:{}", id);
        drinkService.deleteDrinkId(id);
        return "删除成功";
    }

    //文件上传
    //
    @PostMapping(value = "/upload",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE
            })
    public String uploadFile(MultipartFile file) {
        String dest = "D:/upload/";

        String destFileName = dest + file.getOriginalFilename();
        File destFile = new File(destFileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }


    @PostMapping(value = "/batch",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE
            })
    public List<Drink> batchAddNewDrink(MultipartFile file) {
        List<Drink> results = new ArrayList<>();
        try {
//            InputStream inputStream=file.getInputStream();
//            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
//            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
//                line=reader.readLine();
                String[] args = line.split(",");
                Drink drink = Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(args[3])))
                        .build();
//                results.add(drink);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return results;
    }
}
